<template>
  <div class="login_container">
    <div class="login_box">
      <div class="form-box">
        <el-form ref="loginRef" :model="form" :rules="loginrules">
          <el-form-item prop="username">
            <el-input v-model="form.username" placeholder="username"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="form.password" type="password" placeholder="password"></el-input>
          </el-form-item>
          <el-button type="primary" @click="login">登录</el-button>
          <el-button type="danger" @click="reset">重置</el-button>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      form: {
        username: "admin",
        password: "123456"
      },
      //表单的验证规则
      loginrules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 5, max: 15, message: "长度在 5 到 15 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 5, max: 15, message: "长度在 5到 15 个字符", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    reset() {
      this.$refs.loginRef.resetFields();
    },
    login() {
      this.$refs.loginRef.validate(valid => {
        if (!valid) return;
        this.$axios.post("login", this.form).then(res => {
          let res1 = res.data;
          if (res1.meta.status !== 200)
            return this.$message({
              message: "登陆失败！",
              type: "error"
            });
          this.$message({
            message: "登陆成功！",
            type: "success"
          });
          sessionStorage.setItem("token", res1.data.token);
          this.$router.push("/home");
        });
      });
    }
  }
};
</script>
<style scoped>
.login_container {
  height: 100%;
  background-color: #2b4b6b;
}
.login_box {
  width: 450px;
  height: 300px;
  background-color: aliceblue;
  border-radius: 3px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
.form-box {
  width: 100%;
  text-align: center;
  padding: 0px 20px;
  box-sizing: border-box;
  margin-top: 50px;
}
</style>
